package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter{
    @Autowired
    private JwtTool jwtTool;
    @Autowired
    private AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request和Response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2.校验风闻地址是否是开放的地址，如果是，直接放行  有一些地址是开放的：比如 登录
        String uri = request.getPath().toString();
        if(isExclude(uri)){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = request.getHeaders().getFirst("authorization");
        // 4.校验令牌是否有效，无效直接拦截
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 如果无效，拦截
            //提示参数错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //响应状态码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON); //响应JSON类型
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }
        // 4、有效，获取用户ID，并封装到请求头，可以传递给下游服务
        String userInfo = userId.toString();
        exchange.mutate().request(builder -> builder.header("user-info",userInfo));
        // 5.放行
        return chain.filter(exchange);
    }

    /**
     * 匹配指定地址是否需要进行拦截
     * @param uri
     * @return true 不拦截  false 拦截
     */
    private boolean isExclude(String uri) {
        return authProperties.getExcludePaths()
                .stream()
                .anyMatch(ep -> antPathMatcher.match(ep,uri));
    }
}